/*
 * Copyright 2006-2007 S W McIlroy
 * Licensed  under the  Apache License,  Version 2.0  (the "License");
 * you may not use  this file  except in  compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed  under the  License is distributed on an "AS IS" BASIS,
 * WITHOUT  WARRANTIES OR CONDITIONS  OF ANY KIND, either  express  or
 * implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mockfu;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;

import org.objectweb.asm.Type;

/**
 * A method specification that includes argument constraints.
 */
public class ConstrainedMethod
{
    private final List<Matcher<Object>> matchers;
    private final Class<?> owner;
    private final String name;
    private final Class<?>[] parameterTypes;

    private static Class<?>[] types( Object[] args )
    {
        Class<?>[] types = new Class[args.length];
        for( int i = 0 ; i < args.length ; i++ )
        {
            Object arg = args[i];
            types[i] = arg == null ? Object.class : arg.getClass();
        }
        return types;
    }

    /**
     * Creates a constrained method from a method and argument constraints.
     *
     * @param method
     * @param args
     */
    public ConstrainedMethod( Method method, Object... args )
    {
        this( method.getName(), method.getDeclaringClass(), method.getParameterTypes(), args );
    }

    /**
     * Creates a constrained method from a constructor and argument constraints.
     *
     * @param constructor
     * @param args
     */
    public ConstrainedMethod( Constructor<?> constructor, Object... args )
    {
        this( constructor.getDeclaringClass(), constructor.getParameterTypes(), args );
    }

    /**
     * Creates a constrained method from a constructor in the specified class whose signature
     * matches the types of the argument constraints.
     *
     * @param owner
     * @param args
     */
    public ConstrainedMethod( Class<?> owner, Object... args )
    {
        this( owner, types( args ), args );
    }

    /**
     * Creates a constrained method from a constructor in the specified class whose signature
     * matches the specified parameter types and argument constraints.
     *
     * @param owner
     * @param parameterTypes
     * @param args
     */
    public ConstrainedMethod( Class<?> owner, Class<?>[] parameterTypes, Object... args )
    {
        this( "<init>", owner, parameterTypes, args );
    }

    /**
     * Creates a constrained method from a method with the specified class and name whose signature
     * matches the types of the argument constraints.
     *
     * @param methodName
     * @param klas
     * @param args
     */
    public ConstrainedMethod( String methodName, Class<?> klas, Object... args )
    {
        this( methodName, klas, types( args ), args );
    }

    /**
     * Creates a constrained method from a method with the specified class and name whose signature
     * matches the specified parameter types and argument constraints.
     *
     * @param name
     * @param owner
     * @param parameterTypes
     * @param args
     */
    public ConstrainedMethod( String name, Class<?> owner, Class<?>[] parameterTypes,
                               Object... args )
    {
        try
        {
            this.owner = owner;
            this.name = name;
            this.parameterTypes = parameterTypes;
            matchers = Constraints.getMatchers( args );
            if( !Constraints.current().isEmpty() )
                throw new IllegalStateException( "Too many constraints" );
        }
        finally
        {
            Constraints.current().clear();
        }
    }

    /**
     * Returns the class in which this method is declared.
     *
     * @return
     */
    public Class<?> getDeclaringClass()
    {
        return owner;
    }

    /**
     * Returns the name of this method, or "&lt;init&gt;" if a constructor.
     *
     * @return
     */
    public String getName()
    {
        return name;
    }

    boolean isMethod( String methodName, Type[] argumentTypes )
    {
        if( methodName == null )
            methodName = "<init>";

        if( !methodName.equals( name ) )
            return false;

        if( argumentTypes.length != parameterTypes.length )
            return false;

        for( int i = 0 ; i < parameterTypes.length ; i++ )
        {
            if( !argumentTypes[i].getClassName().equals( argumentTypes[i].getClassName() ) )
                return false;
        }

        return true;
    }

    /**
     * Returns <tt>true</tt> if this method's argument constraints match the given actual
     * arguments.
     *
     * @param args
     * @return
     */
    public boolean matches( Object... args )
    {
        if( args.length != matchers.size() )
            throw new IllegalArgumentException( "Number of arguments does not match" );

        /*
         * temporarily disable expectation increments so that mock arguments can be interrogated by
         * matchers without affecting the expectations for that mock
         */
        boolean previousIncrementable = InvocationContext.setIncrementable( false );
        try
        {
            for( int i = 0 ; i < args.length ; i++ )
            {
                if( !matchers.get( i ).matches( args[i] ) )
                    return false;
            }
            return true;
        }
        finally
        {
            InvocationContext.setIncrementable( previousIncrementable );
        }
    }
}
